<template>
  <div class="employee-table-container">
    <div class="table-header">
      <h2>员工车位预约信息</h2>
      <div class="table-actions">
        <a-input-search
          v-model:value="searchText"
          placeholder="搜索员工姓名或车牌号"
          style="width: 250px"
          @search="onSearch"
        />
        <a-button @click="showImportModal">
          <template #icon><ImportOutlined /></template>
          导入
        </a-button>
        <a-button @click="downloadTemplate">
          <template #icon><DownloadOutlined /></template>
          下载导入模板
        </a-button>
        <a-button type="primary" @click="showAddModal">
          <template #icon><PlusOutlined /></template>
          新增员工
        </a-button>
      </div>
    </div>

    <a-modal
      v-model:visible="importModalVisible"
      title="导入员工信息"
      :footer="null"
      @cancel="handleImportCancel"
    >
      <div class="import-container">
        <div class="import-instructions">
          <p>请上传包含员工信息的Excel文件，文件中必须包含以下列：</p>
          <ul>
            <li>员工姓名</li>
            <li>车牌号</li>
            <li>手机号</li>
          </ul>
          <p>
            您可以<a @click="downloadTemplate">下载模板</a>以确保数据格式正确。
          </p>
        </div>
        <a-upload-dragger
          :multiple="false"
          :before-upload="beforeUpload"
          :show-upload-list="false"
          accept=".xlsx,.xls"
        >
          <p class="ant-upload-drag-icon">
            <InboxOutlined />
          </p>
          <p class="ant-upload-text">点击或拖拽文件到此区域上传</p>
          <p class="ant-upload-hint">仅支持 .xlsx 或 .xls 文件</p>
        </a-upload-dragger>
        <div v-if="uploadedFile" class="file-info">
          <p><FileOutlined /> {{ uploadedFile.name }}</p>
          <a-button type="primary" @click="parseAndImport" :loading="importing">
            开始导入
          </a-button>
        </div>
      </div>
    </a-modal>

    <a-modal
      v-model:visible="addModalVisible"
      title="新增员工"
      @ok="handleAddSubmit"
      @cancel="resetAddForm"
      :confirmLoading="addLoading"
    >
      <a-form
        :model="addForm"
        name="addEmployeeForm"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
        ref="addFormRef"
        :rules="addFormRules"
      >
        <a-form-item label="员工姓名" name="name">
          <a-input v-model:value="addForm.name" placeholder="请输入员工姓名" />
        </a-form-item>

        <a-form-item label="车牌号" name="plateNumber">
          <a-input
            v-model:value="addForm.plateNumber"
            placeholder="请输入车牌号"
          />
        </a-form-item>

        <a-form-item label="手机号" name="phone">
          <a-input v-model:value="addForm.phone" placeholder="请输入手机号" />
        </a-form-item>

        <a-form-item label="是否新能源车" name="isNewEnergy">
          <a-switch v-model:checked="addForm.isNewEnergy" />
        </a-form-item>
      </a-form>
    </a-modal>

    <a-modal
      v-model:visible="editModalVisible"
      title="编辑员工"
      @ok="handleEditSubmit"
      @cancel="resetEditForm"
      :confirmLoading="editLoading"
    >
      <a-form
        :model="editForm"
        name="editEmployeeForm"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
        ref="editFormRef"
        :rules="addFormRules"
      >
        <a-form-item label="员工姓名" name="name">
          <a-input v-model:value="editForm.name" placeholder="请输入员工姓名" />
        </a-form-item>

        <a-form-item label="车牌号" name="plateNumber">
          <a-input
            v-model:value="editForm.plateNumber"
            placeholder="请输入车牌号"
          />
        </a-form-item>

        <a-form-item label="手机号" name="phone">
          <a-input v-model:value="editForm.phone" placeholder="请输入手机号" />
        </a-form-item>

        <a-form-item label="是否新能源车" name="isNewEnergy">
          <a-switch v-model:checked="editForm.isNewEnergy" />
        </a-form-item>

        <a-form-item label="预约权限" name="isDisabled">
          <a-switch
            :checked="!editForm.isDisabled"
            @change="(checked) => (editForm.isDisabled = !checked)"
            checked-children="正常"
            un-checked-children="禁用"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <a-modal
      v-model:visible="deleteModalVisible"
      title="确认删除"
      okText="删除"
      okType="danger"
      @ok="confirmDelete"
      @cancel="cancelDelete"
      :confirmLoading="deleteLoading"
    >
      <p>
        您确定要删除员工"{{
          deleteTarget?.name || ""
        }}"的信息吗？此操作不可恢复。
      </p>
    </a-modal>

    <a-table
      :columns="columns"
      :data-source="filteredData"
      :pagination="false"
      :loading="loading"
      row-key="id"
      bordered
    >
      <!-- 车牌号信息 -->
      <template #bodyCell="{ column, record }">
        <!-- 新能源标识 -->
        <template v-if="column.dataIndex === 'plateNumber'">
          <span>
            {{ record.plateNumber }}
            <a-tag v-if="record.isNewEnergy" color="green">新能源</a-tag>
          </span>
        </template>

        <!-- 季度额度 -->
        <template v-if="column.dataIndex === 'currentQuotaRemaining'">
          <a-progress
            :percent="
              (record.currentQuotaRemaining / record.currentQuotaTotal) * 100
            "
            :format="
              (percent) =>
                `${record.currentQuotaRemaining}/${record.currentQuotaTotal}`
            "
            size="small"
            :status="
              getQuotaStatus(
                record.currentQuotaRemaining,
                record.currentQuotaTotal
              )
            "
          />
        </template>

        <!-- 下季度额度 -->
        <template v-if="column.dataIndex === 'nextQuotaRemaining'">
          <a-progress
            :percent="(record.nextQuotaRemaining / record.nextQuotaTotal) * 100"
            :format="
              (percent) =>
                `${record.nextQuotaRemaining}/${record.nextQuotaTotal}`
            "
            size="small"
            :status="
              getQuotaStatus(record.nextQuotaRemaining, record.nextQuotaTotal)
            "
          />
        </template>

        <!-- 状态列修改：显示开关代替标签 -->
        <template v-if="column.dataIndex === 'status'">
          <div class="status-cell">
            <a-switch
              size="small"
              :checked="!record.isDisabled"
              @change="(checked) => handleToggleUserDisabled(record, checked)"
              :checkedChildren="'启用'"
              :unCheckedChildren="'禁用'"
            />
            <!-- <a-tag v-if="record.isDisabled" color="red" class="status-tag">已禁用</a-tag>
            <a-tag v-else color="green" class="status-tag">正常</a-tag> -->
          </div>
        </template>

        <!-- 操作列：移除开关 -->
        <template v-if="column.dataIndex === 'actions'">
          <a-space>
            <a-button type="link" size="small" @click="viewUserDetail(record)"
              >详情</a-button
            >
            <a-button type="link" size="small" @click="showEditModal(record)"
              >编辑</a-button
            >
            <a-button
              type="link"
              size="small"
              danger
              @click="showDeleteModal(record)"
              >删除</a-button
            >
          </a-space>
        </template>
      </template>
    </a-table>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive } from "vue";
import { useRouter } from "vue-router";
import {
  PlusOutlined,
  ImportOutlined,
  DownloadOutlined,
  InboxOutlined,
  FileOutlined,
} from "@ant-design/icons-vue";
import { message, Form } from "ant-design-vue";
import * as XLSX from "xlsx";
import { saveAs } from "file-saver";
import { getUserList, addUser, updateUser } from "../api/index"; // 导入updateUser API

// 获取路由器
const router = useRouter();

// 表格列定义
const columns = [
  {
    title: "员工姓名",
    dataIndex: "name",
    key: "name",
    sorter: (a, b) => a.name.localeCompare(b.name),
  },
  {
    title: "车牌号",
    dataIndex: "plateNumber",
    key: "plateNumber",
  },
  {
    title: "手机号",
    dataIndex: "phone",
    key: "phone",
  },
  {
    title: "本季度剩余额度",
    dataIndex: "currentQuotaRemaining",
    key: "currentQuotaRemaining",
    sorter: (a, b) => a.currentQuotaRemaining - b.currentQuotaRemaining,
  },
  {
    title: "下季度剩余额度",
    dataIndex: "nextQuotaRemaining",
    key: "nextQuotaRemaining",
    sorter: (a, b) => a.nextQuotaRemaining - b.nextQuotaRemaining,
  },
  {
    title: "状态",
    dataIndex: "status",
    key: "status",
    align: "center",
    width: 100, // 确保列宽足够容纳开关和标签
    filters: [
      { text: "正常", value: false },
      { text: "已禁用", value: true },
    ],
    onFilter: (value, record) => record.isDisabled === value,
  },
  {
    title: "操作",
    dataIndex: "actions",
    key: "actions",
    fixed: "right",
    width: 120,
  },
];

// 表格数据源
const dataSource = ref([]);
const loading = ref(false);
const searchText = ref("");

const filteredData = computed(() => {
  if (!searchText.value) {
    return dataSource.value;
  }
  const searchValue = searchText.value.toLowerCase();
  return dataSource.value.filter(
    (item) =>
      item.name.toLowerCase().includes(searchValue) ||
      item.plateNumber.toLowerCase().includes(searchValue)
  );
});

// 根据剩余额度返回状态
const getQuotaStatus = (remaining, total) => {
  const percent = (remaining / total) * 100;
  if (percent <= 20) return "exception";
  if (percent <= 50) return "warning";
  return "normal";
};

// 封装获取员工列表函数
const fetchUserList = (searchValue = "") => {
  loading.value = true;

  // 构建查询参数
  const params = {
    page: 1,
    per_page: 1000,
  };

  // 如果有搜索关键词，则添加到参数中
  if (searchValue) {
    params.search = searchValue;
  }

  // 调用API获取员工列表
  getUserList(params)
    .then((response) => {
      // response.data.data 是列表数据，其中的一项是：
      // {
      //   "id": 10,
      //   "name": "测试用户1",
      //   "phone": "17710000008",
      //   "license_plate": "Aww111",
      //   "is_new_energy": false,
      //   "created_at": "2025-05-14 09:12:29",
      //   "deleted_at": null,
      //   "updated_at": "2025-05-17 11:57:27",
      //   "is_active": true,
      //   "current_quarter_quota": "18.0",
      //   "next_quarter_quota": "26.0",
      //   "current_quarter_quota_remaining": "15.5",
      //   "next_quarter_quota_remaining": "26.0",
      //   "cancel_quota": "8",
      //   "is_absent": false
      // }
      if (response && response.code === 200 && response.data.data) {
        // 使用API返回的数据，调整字段映射
        dataSource.value = response.data.data.map((item) => ({
          id: item.id,
          name: item.name || item.username, // 支持name或username字段
          plateNumber: item.license_plate || item.plateNumber, // 支持不同命名风格
          isNewEnergy: item.is_new_energy || item.isNewEnergy || false,
          phone: item.phone || item.mobile || "",
          currentQuotaRemaining:
            item.current_quarter_quota_remaining ||
            item.currentQuotaRemaining ||
            0,
          currentQuotaTotal:
            item.current_quarter_quota || item.currentQuotaTotal || 30,
          nextQuotaRemaining:
            item.next_quarter_quota_remaining || item.nextQuotaRemaining || 0,
          nextQuotaTotal: item.next_quarter_quota || item.nextQuotaTotal || 30,
          cancelCount: item.cancel_quota || item.cancelCount || 0,
          isDisabled: !item.is_active || item.isDisabled || false,
        }));
        console.log(dataSource.value);

        message.success("员工数据加载成功");
      } else {
        message.error("获取员工数据失败：" + (response.message || "未知错误"));
        // 加载失败时使用空数组
        dataSource.value = [];
      }
    })
    .catch((error) => {
      console.error("获取员工数据出错:", error);
      message.error("获取员工数据失败，请检查网络连接");
      dataSource.value = [];
    })
    .finally(() => {
      loading.value = false;
    });
};

// 修改搜索函数，直接调用API查询而不是本地筛选
const onSearch = (value) => {
  searchText.value = value;
  fetchUserList(value); // 使用搜索值调用API
};

// 导入功能相关状态
const importModalVisible = ref(false);
const uploadedFile = ref(null);
const importing = ref(false);

// 新增员工相关状态
const addModalVisible = ref(false);
const addLoading = ref(false);
const addFormRef = ref(null);

// 新增员工表单数据
const addForm = reactive({
  name: "",
  plateNumber: "",
  phone: "",
  isNewEnergy: false,
});

// 表单验证规则
const addFormRules = {
  name: [
    { required: true, message: "请输入员工姓名", trigger: "blur" },
    { min: 2, max: 20, message: "姓名长度应为2-20个字符", trigger: "blur" },
  ],
  plateNumber: [
    { required: true, message: "请输入车牌号", trigger: "blur" },
    {
      pattern: /^[\u4e00-\u9fa5][A-Z][A-Z0-9]{4,5}[A-Z0-9挂学警港澳]$/,
      message: "请输入正确格式的车牌号",
      trigger: "blur",
    },
  ],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
};

// 显示导入对话框
const showImportModal = () => {
  importModalVisible.value = true;
  uploadedFile.value = null;
};

// 处理导入取消
const handleImportCancel = () => {
  importModalVisible.value = false;
  uploadedFile.value = null;
};

// 处理文件上传前检查
const beforeUpload = (file) => {
  const isExcel =
    file.type ===
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
    file.type === "application/vnd.ms-excel";

  if (!isExcel) {
    message.error("只能上传Excel文件!");
    return Upload.LIST_IGNORE;
  }

  uploadedFile.value = file;
  return false; // 阻止自动上传
};

// 解析并导入Excel文件
const parseAndImport = async () => {
  if (!uploadedFile.value) {
    message.error("请先上传文件!");
    return;
  }

  importing.value = true;

  try {
    const reader = new FileReader();

    reader.onload = (e) => {
      try {
        const data = new Uint8Array(e.target.result);
        const workbook = XLSX.read(data, { type: "array" });

        // 获取第一个工作表
        const worksheetName = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[worksheetName];

        // 将工作表转为JSON
        const jsonData = XLSX.utils.sheet_to_json(worksheet);

        if (jsonData.length === 0) {
          message.error("上传的文件中没有数据!");
          importing.value = false;
          return;
        }

        // 验证必要字段
        const requiredFields = ["员工姓名", "车牌号", "手机号"];
        const firstRow = jsonData[0];

        const missingFields = requiredFields.filter(
          (field) => !(field in firstRow)
        );

        if (missingFields.length > 0) {
          message.error(`上传的文件缺少必要字段: ${missingFields.join(", ")}`);
          importing.value = false;
          return;
        }

        // 处理导入数据
        const importPromises = jsonData.map((row) => {
          // 读取Excel数据
          const name = row["员工姓名"]?.toString().trim() || "";
          const plateNumber = row["车牌号"]?.toString().trim() || "";
          const phone = row["手机号"]?.toString().trim() || "";

          // 检查是否新能源字段是否存在，并转换为布尔值
          // 如果字段不存在，则根据车牌号自动判断
          let isNewEnergy = false;
          if ("是否新能源" in row) {
            // 将0/1值转换为布尔值
            isNewEnergy = Boolean(Number(row["是否新能源"]));
          } else {
            // 备用判断逻辑：新能源车牌通常为8位，或者以D/F开头
            isNewEnergy =
              plateNumber.length >= 8 ||
              plateNumber.startsWith("沪D") ||
              plateNumber.startsWith("沪F");
          }

          // 构建API参数
          const params = {
            name: name,
            phone: phone,
            license_plate: plateNumber,
            is_new_energy: isNewEnergy === "true" || isNewEnergy ? true : false, // 确保为布尔值
          };
          console.log(typeof params.test);

          // 返回API调用Promise
          return addUser(params);
        });

        // 执行所有导入请求
        Promise.allSettled(importPromises)
          .then((results) => {
            // 计算成功和失败的数量
            const successful = results.filter(
              (r) => r.status === "fulfilled" && r.value.code === 200
            ).length;
            const failed = results.length - successful;

            if (successful === results.length) {
              message.success(`成功导入 ${successful} 条员工数据!`);
            } else if (successful > 0) {
              message.warning(
                `部分导入成功: ${successful}条成功, ${failed}条失败`
              );
            } else {
              message.error("导入失败，请检查数据格式是否正确");
            }

            // 刷新列表
            fetchUserList(searchText.value);

            // 关闭模态框
            importModalVisible.value = false;
            importing.value = false;
          })
          .catch((error) => {
            console.error("批量导入出错:", error);
            message.error("导入过程出错，请重试!");
            importing.value = false;
          });
      } catch (error) {
        console.error("解析Excel文件出错:", error);
        message.error("解析文件失败，请检查文件格式是否正确!");
        importing.value = false;
      }
    };

    reader.onerror = () => {
      message.error("读取文件失败!");
      importing.value = false;
    };

    reader.readAsArrayBuffer(uploadedFile.value);
  } catch (error) {
    console.error("导入过程出错:", error);
    message.error("导入过程出错，请重试!");
    importing.value = false;
  }
};

// 下载导入模板
const downloadTemplate = () => {
  // 创建工作簿和工作表
  const workbook = XLSX.utils.book_new();

  // 创建模板数据
  const templateData = [
    {
      员工姓名: "张三",
      车牌号: "沪A12345",
      手机号: "13812345678",
      是否新能源: 0, // 0表示否
    },
    {
      员工姓名: "李四(新能源车示例)",
      车牌号: "沪AD12345",
      手机号: "13987654321",
      是否新能源: 1, // 1表示是
    },
  ];

  // 将数据转换为工作表
  const worksheet = XLSX.utils.json_to_sheet(templateData);

  // 设置列宽
  const colWidths = [
    { wch: 25 }, // 员工姓名列宽
    { wch: 15 }, // 车牌号列宽
    { wch: 15 }, // 手机号列宽
    { wch: 12 }, // 是否新能源列宽
  ];

  worksheet["!cols"] = colWidths;

  // 将工作表添加到工作簿
  XLSX.utils.book_append_sheet(workbook, worksheet, "员工信息");

  // 生成xlsx文件并下载
  const excelBuffer = XLSX.write(workbook, { bookType: "xlsx", type: "array" });
  const blob = new Blob([excelBuffer], { type: "application/octet-stream" });

  saveAs(blob, "员工信息导入模板.xlsx");

  message.success("模板下载成功!");
};

// 显示新增员工对话框
const showAddModal = () => {
  addModalVisible.value = true;
};

// 重置表单
const resetAddForm = () => {
  addModalVisible.value = false;
  addFormRef.value && addFormRef.value.resetFields();
};

// 处理表单提交，修改为调用API后刷新列表
const handleAddSubmit = () => {
  addFormRef.value &&
    addFormRef.value
      .validate()
      .then(() => {
        addLoading.value = true;

        // 准备请求参数
        const params = {
          name: addForm.name,
          phone: addForm.phone,
          license_plate: addForm.plateNumber,
          test: 111111111,
          is_new_energy: addForm.isNewEnergy,
        };

        console.log(typeof addForm.isNewEnergy);
        // 调用添加用户API
        addUser(params)
          .then((response) => {
            if (response && response.code === 200) {
              message.success("员工添加成功");
              // 重置表单并关闭对话框
              resetAddForm();
              // 添加成功后刷新列表
              fetchUserList(searchText.value);
            } else {
              message.error(
                "添加员工失败：" + (response.message || "未知错误")
              );
            }
          })
          .catch((error) => {
            console.error("添加员工出错:", error);
            message.error("添加员工失败，请检查网络连接");
          })
          .finally(() => {
            addLoading.value = false;
          });
      })
      .catch((error) => {
        console.log("验证失败", error);
      });
};

// 检测是否为新能源车牌
const detectNewEnergy = () => {
  const plateNumber = addForm.plateNumber;
  if (plateNumber) {
    // 新能源车牌通常为8位，或以特定字母开头
    addForm.isNewEnergy =
      plateNumber.length >= 8 ||
      plateNumber.includes("D") ||
      plateNumber.includes("F");
  }
};

// 编辑员工相关状态
const editModalVisible = ref(false);
const editLoading = ref(false);
const editFormRef = ref(null);
const currentEditId = ref(null);

// 编辑员工表单数据
const editForm = reactive({
  name: "",
  plateNumber: "",
  phone: "",
  isNewEnergy: false,
  isDisabled: false,
});

// 删除员工相关状态
const deleteModalVisible = ref(false);
const deleteLoading = ref(false);
const deleteTarget = ref(null);

// 显示编辑员工对话框
const showEditModal = (record) => {
  // 设置当前编辑的员工ID
  currentEditId.value = record.id;

  // 填充表单数据
  editForm.name = record.name;
  editForm.plateNumber = record.plateNumber;
  editForm.phone = record.phone;
  editForm.isNewEnergy = record.isNewEnergy;
  editForm.isDisabled = record.isDisabled;

  // 显示对话框
  editModalVisible.value = true;
};

// 重置编辑表单
const resetEditForm = () => {
  editModalVisible.value = false;
  currentEditId.value = null;
  editFormRef.value && editFormRef.value.resetFields();
};

// 处理编辑表单提交
const handleEditSubmit = () => {
  editFormRef.value &&
    editFormRef.value
      .validate()
      .then(() => {
        editLoading.value = true;

        // 准备请求参数 - 使用API需要的字段名格式
        const params = {
          name: editForm.name,
          phone: editForm.phone,
          license_plate: editForm.plateNumber,
          is_new_energy: editForm.isNewEnergy,
          is_active: !editForm.isDisabled, // 注意这里的取反关系：isDisabled=true 对应 is_active=false
        };

        // 调用API更新员工信息
        updateUser(currentEditId.value, params)
          .then((response) => {
            if (response && response.code === 200) {
              // 查找当前编辑的员工
              const index = dataSource.value.findIndex(
                (item) => item.id === currentEditId.value
              );

              if (index !== -1) {
                // 创建更新后的员工记录
                const updatedEmployee = {
                  ...dataSource.value[index], // 保留原有数据
                  name: editForm.name,
                  plateNumber: editForm.plateNumber,
                  isNewEnergy: editForm.isNewEnergy,
                  phone: editForm.phone,
                  isDisabled: editForm.isDisabled,
                };

                // 更新数据源
                dataSource.value[index] = updatedEmployee;
                dataSource.value = [...dataSource.value]; // 强制刷新表格

                // 重置表单并关闭对话框
                resetEditForm();
                message.success("员工信息更新成功");
              } else {
                message.error("找不到要编辑的员工");
              }
            } else {
              message.error(
                "更新员工信息失败：" + (response.message || "未知错误")
              );
            }
          })
          .catch((error) => {
            console.error("更新员工信息出错:", error);
            message.error("更新员工信息失败，请检查网络连接");
          })
          .finally(() => {
            editLoading.value = false;
          });
      })
      .catch((error) => {
        console.log("验证失败", error);
      });
};

// 显示删除确认对话框
const showDeleteModal = (record) => {
  deleteTarget.value = record;
  deleteModalVisible.value = true;
};

// 取消删除
const cancelDelete = () => {
  deleteTarget.value = null;
  deleteModalVisible.value = false;
};

// 确认删除
const confirmDelete = () => {
  if (!deleteTarget.value) {
    return;
  }

  deleteLoading.value = true;
  updateUser(deleteTarget.value.id, {
    is_delete: true,
  })
    .then((response) => {
      if (response && response.code === 200) {
        dataSource.value = dataSource.value.filter(
          (item) => item.id !== deleteTarget.value.id
        );
        message.success(`员工"${deleteTarget.value.name}"已删除`);
        cancelDelete();
        deleteLoading.value = false;
        fetchUserList(searchText.value);
      } else {
        message.error("删除员工失败：" + (response.message || "未知错误"));
      }
    })
    .catch((error) => {
      console.error("删除员工出错:", error);
      message.error("删除员工失败，请检查网络连接");
    });
};

// 查看用户详情
const viewUserDetail = (record) => {
  router.push(`/user/${record.id}`);
};

// 定义函数
const handleToggleUserDisabled = (record, checked) => {
  // 注意：checked为true表示启用，false表示禁用
  const index = dataSource.value.findIndex((item) => item.id === record.id);
  if (index !== -1) {
    // 调用API更新用户状态
    updateUser(record.id, {
      is_active: checked, // true表示启用，false表示禁用
    })
      .then((response) => {
        if (response && response.code === 200) {
          // 更新本地状态
          dataSource.value[index].isDisabled = !checked;

          // 克隆数组以触发重新渲染
          dataSource.value = [...dataSource.value];

          // 显示成功消息
          const status = !checked ? "禁用" : "启用";
          message.success(`已${status}用户"${record.name}"的预约权限`);
        } else {
          message.error("更新状态失败：" + (response.message || "未知错误"));
        }
      })
      .catch((error) => {
        console.error("更新用户状态出错:", error);
        message.error("更新用户状态失败，请检查网络连接");
      });
  }
};

// 在组件挂载时加载数据
onMounted(() => {
  fetchUserList();
});
</script>

<style scoped>
:deep(.ant-progress.ant-progress-show-info .ant-progress-outer) {
  margin-inline-end: calc(-2em - 30px);
  padding-inline-end: calc(2em + 30px);
}
.employee-table-container {
  padding: 24px 0;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.table-header h2 {
  margin: 0;
  color: var(--text-color);
  font-size: 20px;
}

.table-actions {
  display: flex;
  gap: 12px;
}

/* 导入模态窗口样式 */
.import-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.import-instructions {
  background-color: #f5f5f5;
  padding: 16px;
  border-radius: 4px;
  margin-bottom: 12px;
}

.import-instructions a {
  color: var(--primary-color);
  cursor: pointer;
}

.import-instructions ul {
  margin: 8px 0;
  padding-left: 20px;
}

.file-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 16px;
  background-color: #f5f5f5;
  padding: 10px;
  border-radius: 4px;
}

/* 添加状态单元格样式 */
.status-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.status-tag {
  margin-left: 4px;
}
</style>